<template>
  <div>
    <div ref="chartRef" style="width: 100%; height: 450px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

const chartRef = ref(null);

onMounted(async () => {
  const chart = echarts.init(chartRef.value);

  try {
    // 从API获取数据
    const response = await axios.get('/api/queryAllSalesPower'); // 替换为你的API地址
    const rawData = response.data.data;

    // 数据处理：按年份分组数据
    const years = [...new Set(rawData.map((item) => item.year))];
    const powerTrains = [...new Set(rawData.map((item) => item.powerTrain))];
    const dataByPowerTrain = powerTrains.map((powerTrain) =>
      years.map((year) => {
        const entry = rawData.find(
          (item) => item.year === year && item.powerTrain === powerTrain
        );
        return entry ? entry.value : 0;
      })
    );

    // 计算每年的总和
    const totalData = years.map((_, yearIndex) =>
      dataByPowerTrain.reduce((sum, powerTrainData) => sum + powerTrainData[yearIndex], 0)
    );

    // 构建堆叠柱状图的 series 数据
    const series = powerTrains.map((powerTrain, index) => ({
      name: powerTrain,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      itemStyle: {
        color: [`#fdffab`, `#8c82fc`, `#62d2a2`][index % 3] // 指定不同颜色给每个系列
      },
      label: {
        show: true,
        formatter: (params) => `${((params.value / totalData[params.dataIndex]) * 100).toFixed(1)}%`,
      },
      data: dataByPowerTrain[index].map((value, dataIndex) =>
        totalData[dataIndex] <= 0 ? 0 : value
      ),
    }));

    // ECharts 配置
    const option = {
      title: {
        text: '不同类型的新能源汽车销售占比',
        top: 30,
        left: 'center',
        textStyle: {
          color: '#FFFFFF', // 标题文字颜色设置为白色
          fontFamily: 'YouYuan'
        },
      },
      legend: {
        data: powerTrains,
        top: 70,
        textStyle: {
          color: '#FFFFFF' // 图例文字颜色为白色
        }
      },
      grid: {
        left: '20%',
        right: '5%',
        top: 120,
        bottom: 20,
      },
      xAxis: {
        type: 'category',
        data: years,
        name: 'Year',
        axisLabel: {
          textStyle: {
            color: '#FFFFFF' // x轴标签颜色设置为白色
          }
        }
      },
      yAxis: {
        type: 'value',
        name: 'Proportion (%)',
        axisLabel: {
          textStyle: {
            color: '#FFFFFF' // y轴标签颜色设置为白色
          }
        }
      },
      series,
    };

    chart.setOption(option);
  } catch (error) {
    console.error('数据加载失败', error);
  }
});
</script>

<style scoped>
h3 {
  text-align: center;
}
</style>

